/**
 *
 * @author Romulus
 */
package org.sais.eswn.net;

import org.sais.eswn.core.GameCore;
import java.io.*;
import java.net.*;
import javax.swing.*;

public abstract class Sock extends Thread {

    public final boolean debug = true;
    protected ISockCallback mCaller;
    protected GameCore mCore = null;
    protected Socket mSocket;
    protected MessageDispatcher mDispatcher;
    protected String mPlayerName;
    protected boolean showDialog = true;

    public abstract void closeSocket();

    public GameCore getCore() {
        return mCore;
    }

    public Socket getSocket() {
        return mSocket;
    }

    public String Fix(String instr) {
        for (int i = 0; i < instr.length(); ++i) {
            if (instr.charAt(i) == '$') {
                return instr.substring(i);
            }
        }
        return instr;
    }

    abstract public void scan();/*{
    /*try {
    BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "Unicode"));
    String instr;
    while ((instr = in.readLine()) != null) {
    instr = Fix(instr);
    if (debug) {
    System.out.println(instr);
    }
    new MessageDispatcher(instr, this.mSocket, this);
    }
    } catch (SocketException ex) {
    if (ex.getMessage().equals("Connection reset")) {
    JOptionPane.showMessageDialog(null, ex.getMessage(),"scan() in Sock", JOptionPane.ERROR_MESSAGE);
    }
    } catch (IOException ex) {
    ex.printStackTrace();
    JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "scan() in Sock", JOptionPane.ERROR_MESSAGE);
    }
    }*/


    public void send(Socket soc, String message) {
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream(), "Unicode"));
            out.write(message);
            out.newLine();
            out.flush();
        } catch (SocketException ex) {
            ex.printStackTrace();
            return;
        } catch (Exception ex) {
            ex.printStackTrace();
            if (showDialog) {
                JOptionPane.showMessageDialog(null, ex.getClass() + "\n" + ex.getMessage(), "send() in Sock", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    @Override
    public void run() {
    }

    public void setMessage(String message) {
        mCaller.setMessage(message);
    }

    public String getPlayerName() {
        return mPlayerName;
    }
}

